.PHONY: help
.DEFAULT_GOAL := help
BATS_VERSION = c706d1470dd1376687776bbe985ac22d09780327 #v1.1.0
BATS_ASSERT = 9f88b4207da750093baabc4e3f41bf68f0dd3630 #v0.3.0
BATS_SUPPORT = 004e707638eedd62e0481e8cdc9223ad471f12ee #v0.3.0
LTS_ALPINE ?= 12-alpine

help: ## Display this help text
	@grep -E '^[a-zA-Z_-]+[%]?:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'

bats: ## Install bats in the project itself
	@echo "Cloning bats-core"
	@[ -d $(CURDIR)/bats-core ] \
		|| git clone -n https://github.com/bats-core/bats-core.git $(CURDIR)/bats-core
	@cd $(CURDIR)/bats-core \
		&& git fetch --all \
		&& git checkout -B v1.1.0 ${BATS_VERSION}

bats-assert: ##Install bats-assert in the project itself
	@echo "Clonning bats-assert"
	@[ -d $(CURDIR)/tests/test_helper/bats-assert ] \
		|| git clone -n https://github.com/ztombol/bats-assert $(CURDIR)/tests/test_helper/bats-assert
	@cd $(CURDIR)/tests/test_helper/bats-assert \
		&& git fetch --all \
		&& git checkout -B v0.3.0 ${BATS_ASSERT}

bats-support: ##Install bats-support in the project itself
	@echo "Clonning bats-support"
	@[ -d $(CURDIR)/tests/test_helper/bats-support ] \
		|| git clone -n https://github.com/ztombol/bats-support $(CURDIR)/tests/test_helper/bats-support
	@cd $(CURDIR)/tests/test_helper/bats-support \
		&& git fetch --all \
		&& git checkout -B v0.3.0 ${BATS_SUPPORT}

prepare-test: bats bats-assert bats-support## Prepare the bats dependencies
	@echo "Pulling Alpine image"
	@docker pull node:${LTS_ALPINE}
	@mkdir -p target

convert-tests-results: ## convert TAP test results to JUnit
	@APP=$*; docker run --rm -e APP=$${APP} -v "$(CURDIR)":/usr/src/app -w /usr/src/app node:${LTS_ALPINE} \
					sh -c 'npm install tap-xunit -g && cat target/results.tap | tap-xunit --package="co.elastic.pipeline.$${APP}" > target/junit-$${APP}-results.xml'

test-%: prepare-test ## Run the tests for the specific app
	@DOCKERFILE=$* bats-core/bin/bats --tap tests | tee target/results.tap
	@$(MAKE) -s convert-tests-results

push-%: prepare-test ## Push the Docker image to the docker.elastic.co repository
	docker push "docker.elastic.co/observability-ci/$*"

all-push: push-golang-mage ## Push all Docker images to the docker.elastic.co repository

all-tests: test-golang-mage ## Run the tests for all the apps

clean: ## Clean autogenerated files/folders
	@rm -rf bats-core
	@rm -rf target
